#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import yaml
from yaml.scanner import ScannerError
from yaml.parser import ParserError
import logging
import asyncio
import easygui
from fileman import Fileman


def get_config(file_name):
    try:
        with open(file_name, 'r', encoding='utf-8') as f:
            data = yaml.safe_load(f)
        return data
    except ScannerError:
        easygui.msgbox("config.yaml - не правильний.\nПеревір помилки тут https://yamlchecker.com \n чи на аналогічному сайті", title="Fileman")
    except ParserError:
        easygui.msgbox("config.yaml - не правильний.\nПеревір помилки тут https://yamlchecker.com \n чи на аналогічному сайті", title="Fileman")
    return None


def save_pid(pid):
    with open("pid", "w") as f:
        f.write(f"{pid}")


async def main():
    print(f"\n Process ID: {os.getpid()} \n\n")
    save_pid(os.getpid())
    config = get_config("config.yaml")
    filemans = []
    for path in config["paths"]:
        if isinstance(path['watch'], list):
            for watch in path['watch']:
                this_path = path
                this_path['watch'] = watch
                filemans.append(Fileman(path))
        else:
            filemans.append(Fileman(path))
    tasks = []
    for fileman in filemans:
        tasks.append(asyncio.create_task(fileman.async_work(config["pause"])))
    for task in tasks:
        await task


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, filename="info_log.txt", filemode="w" ,format="%(asctime)s %(levelname)s %(message)s")
    try:
        print(10)
        asyncio.run(main())
    except KeyboardInterrupt:
        print("Прощавай")
    except:
        file_logger = logging.FileHandler('error_log.txt')
        file_logger.setLevel(logging.ERROR)
        file_formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
        file_logger.setFormatter(file_formatter)
        root_logger = logging.getLogger()
        root_logger.addHandler(file_logger)
        logging.error("", exc_info=True)
        print("Дай файл error_log.txt розробнику https://social.net.ua/users/SergoZar")
    finally:
        save_pid("")
